using System;
using System.IO;
using PackageResources.Pack;

namespace PackageResources
{
    /**
     * 合并工具类
     * 将目录合并为一个文件
     */
    public class PackageTools
    {
        private string _path;
        private string _packagePath;

        /// <summary>
        /// 打包
        /// </summary>
        /// <param name="originDirectory">原目录</param>
        /// <param name="packagePath">打包路径</param>
        /// <returns></returns>
        public bool Package(string originDirectory, string packagePath)
        {
            _path = originDirectory;
            _packagePath = packagePath;
            PathChecker.CheckDirectoryExisting(_path);
            PathChecker.CheckPackagePath(_packagePath);
            PathChecker.CheckFilesExit(_packagePath);

            //制作文件头
            SerializableHeader fileInfoHeader = new SerializableHeader();

            string[] files = Directory.GetFiles(originDirectory, "*.*", SearchOption.AllDirectories);
            //读取保存资源文件，并将文件信息保存到字典中
            long index = 0; //文件索引位置
            foreach (string file in files)
            {
                using (var f = new FileStream(file, FileMode.Open))
                {
                    fileInfoHeader.Add(GetDirectoryNameByPath(file), index, f.Length);
                    index += f.Length;
                }
            }

            //将信息和资源合并到一个文件中
            using (var fileToPack = new FileStream(_packagePath, FileMode.OpenOrCreate))
            {
                //计算配置文件长度并保存
                var fileInfoHeaderBytes = fileInfoHeader.ToBytes();
                //索引文件长度4bytes
                byte[] headerLengthBytes = BitConverter.GetBytes(fileInfoHeaderBytes.LongLength);
                //将所有信息保存到一个文件中
                using (BinaryWriter bw = new BinaryWriter(fileToPack))
                {
                    bw.Write(headerLengthBytes); //头文件长度信息
                    bw.Write(fileInfoHeaderBytes); //头文件
                    foreach (string file in files) //资源文件
                    {
                        using (var f = new FileStream(file, FileMode.Open))
                        {
                            f.CopyTo(fileToPack);
                        }
                    }
                }

                return true;
            }
        }


        /// <summary>
        /// 根据路径获得目录名称
        /// </summary>
        /// <param name="filePath">当前目录</param>
        /// <returns></returns>
        private string GetDirectoryNameByPath(string filePath)
        {
            var c = filePath.ToCharArray();
            var startIndex = _path.Length;
            if (_path[_path.Length - 1] != '/')
            {
                startIndex += 1;
            }

            var s = new string(c, startIndex, filePath.Length - startIndex);
            return s;
        }
    }
}